package 读写锁ReadWriteLock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockDemo {
    private static Lock lock = new ReentrantLock();
    private static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private static Lock readLock = readWriteLock.readLock();
    private static Lock writeLock = readWriteLock.writeLock();

    private int value;

    public int read(Lock lock) {
        try {
            lock.lock();
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return value;
    }

    public void write(Lock lock, int index) {
        try {
            lock.lock();
            Thread.sleep(1000);
            value = index;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ReadWriteLockDemo demo = new ReadWriteLockDemo();

        Runnable readRunnable = new Runnable() {
            @Override
            public void run() {
                demo.read(readLock);// 读读之间不冲突，其他冲突
//                demo.read(lock);// 用这个，就没有读写概念，一律冲突

            }
        };

        Runnable writeRunnable = new Runnable() {
            @Override
            public void run() {
                demo.write(writeLock, (int) (Math.random() * 10));
//                demo.write(lock, (int) (Math.random() * 10));
            }
        };
        long start = System.currentTimeMillis();
        // 400个读线程
        for (int i = 0; i < 400; i++) {
            Thread thread = new Thread(readRunnable);
            thread.start();
        }
        // 2个写线程
        for (int i = 18; i < 20; i++) {
            Thread thread = new Thread(writeRunnable);
            thread.start();
            thread.join();// 主线程等待这2个写线程
        }
        long end = System.currentTimeMillis();
        System.out.println((end - start) / 1000 + "秒");// 3S (3S后，整个程序结束)
    }


}
